package com.bookshop.service;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bookshop.aspect.exception.CustomException;
import com.bookshop.entity.response.TokenEnum;
import com.bookshop.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author g2l
 * @create 2024-01-15 18:36
 */
@Slf4j
@Service
public class AsyncService {

    // 这些方法可以由不同的线程同时执行
    @Async("threadPool01")
    public CompletableFuture refreshVerify(String refreshToken) {
        log.info(Thread.currentThread().getName() + "1运行了");
        TokenEnum refreshVerify = JWTUtil.verify(refreshToken);
        if (refreshVerify != TokenEnum.TOKEN_SUCCESS) {
            throw new CustomException("请去登录").setCode(401);
        }
        return null;
    }

    @Async("threadPool01")
    public CompletableFuture tokenVerify(String token) {
        log.info(Thread.currentThread().getName() + "2运行了");
        TokenEnum tokenVerify = JWTUtil.verify(token);
        if (tokenVerify == TokenEnum.TOKEN_BAD) {
            throw new CustomException("请去登录").setCode(401);
        }
        return null;
    }

    @Async("threadPool01")
    public CompletableFuture<String> compareUsername(String refreshToken, String token) {
        log.info(Thread.currentThread().getName() + "3运行了");
        String phoneNumber = JWTUtil.getUsername(token);
        if (StringUtils.isBlank(phoneNumber) ||
                !phoneNumber.equals(JWTUtil.getUsername(refreshToken).replace("refreshToken", ""))) {
            throw new CustomException("请去登录").setCode(401);
        }
        return CompletableFuture.completedFuture(phoneNumber);
    }
}
